package com.syyo.gulimall.product.exception;


import com.syyo.common.domain.ResultVo;
import com.syyo.common.enums.ResultEnum;
import com.syyo.common.exception.SysException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 统一捕获自定义异常类
 */
@RestControllerAdvice(basePackages = "com.syyo.gulimall.product")
public class ExceptionCatch {

    /**
     * 校验参数
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultVo customException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        Map<Object, Object> errorMap = new HashMap<>();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        fieldErrors.forEach(fieldError -> {
            errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
        });
        ResultVo<Object> resultVo = new ResultVo<>();
        resultVo.setCode(ResultEnum.E_90002.getCode());
        resultVo.setMessage(ResultEnum.E_90002.getMessage());
        resultVo.setData(errorMap);
        return resultVo;
    }

//    /**
//     * 最大的异常
//     */
//    @ExceptionHandler(Throwable.class)
//    public ResultVo customException(Throwable e){
//        ResultVo<Object> resultVo = new ResultVo<>();
//        resultVo.setCode(ResultEnum.FAIL.getCode());
//        resultVo.setMessage(ResultEnum.FAIL.getMessage());
//        resultVo.setData("");
//        return resultVo;
//    }
}
